<?php

/**
 * usuarios actions.
 *
 * @package    dirsac
 * @subpackage usuarios
 * @author     Miguel Flores
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class usuariosActions extends autousuariosActions
{
	protected function processForm(sfWebRequest $request, sfForm $form)
	{
		$form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
		if ($form->isValid())
		{
			$usuario = $form->save();
			$salt = md5(rand(0, 30).date("Y-m-d H:i:s"));
			$pass = $usuario->getPassword();
			
			$usuario->setPassword(md5($salt.$pass));
			$usuario->setSalt($salt);
			
			$user = $request->getParameter('usuario');
    		$cuenta_id = $user['cuenta_id'];
    		$usuario->getId();
    		
    		$bandera = CuentaUsuario::Nuevo($usuario->getId(), $cuenta_id);
			
			$usuario->save();

			$this->redirect('usuarios/edit?id='.$usuario->getId());
		}
	}
	
  public function executeIndex(sfWebRequest $request)
  {
    $this->usuario_list = Doctrine::getTable('Usuario')
      ->createQuery('a')
      ->execute();
  }

  public function executeShow(sfWebRequest $request)
  {
    $this->usuario = Doctrine::getTable('Usuario')->find(array($request->getParameter('id')));
    $this->forward404Unless($this->usuario);
  }

  public function executeNew(sfWebRequest $request)
  {
    $this->form = new UsuarioForm();
  }

  public function executeCreate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST));

    $this->form = new UsuarioForm();
   	
    $this->processForm($request, $this->form);

    $this->setTemplate('new');
  }

  public function executeEdit(sfWebRequest $request)
  {
    $this->forward404Unless($usuario = Doctrine::getTable('Usuario')->find(array($request->getParameter('id'))), sprintf('Object usuario does not exist (%s).', $request->getParameter('id')));
    $this->form = new UsuarioForm($usuario);
    
    $this->cuentas_usuarios = Doctrine::getTable('CuentaUsuario')->createQuery('c')->where("c.usuario_id = '".$usuario->getId()."'")->execute();
  }

  public function executeUpdate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
    $this->forward404Unless($usuario = Doctrine::getTable('Usuario')->find(array($request->getParameter('id'))), sprintf('Object usuario does not exist (%s).', $request->getParameter('id')));
    $this->form = new UsuarioForm($usuario);

    $this->processForm($request, $this->form);

    $this->setTemplate('edit');
  }

  public function executeDelete(sfWebRequest $request)
  {
    $request->checkCSRFProtection();

    $this->forward404Unless($usuario = Doctrine::getTable('Usuario')->find(array($request->getParameter('id'))), sprintf('Object usuario does not exist (%s).', $request->getParameter('id')));
    $usuario->delete();

    $this->redirect('usuarios/index');
  }
}
